package net.oschina.archx.spring.dao;

import net.oschina.archx.spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by Archx on 2015/6/22 0022.
 */
@Repository
public class UserDao {

    private static final String INSERT_SQL = "insert into tb_user (name, age, email) values (?, ?, ?)";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public long insert(final User user) {
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement psst = con.prepareStatement(INSERT_SQL, new String[]{"id"});
                int count = 1;
                psst.setString(count++, user.getName());
                psst.setInt(count++, user.getAge());
                psst.setString(count++, user.getEmail());
                return psst;
            }
        }, keyHolder);
        return keyHolder.getKey().longValue();
    }
}
